#!/usr/bin/env python
# encoding: utf-8

"""Here you find an example of usage of the session manager.

What do you need to use the session manager:
 - import the Session class from the spyro.session module
 - create a session object in the response method
 - operate on the session object as you need
 
Note: thanks to the common interface, you could also switch the storage
backend. The default one is hard-disk based, this means that session data will
be saved on the filesystem. If you like to try out the cookie-based storage
backend, just change the configuration by adding:

    sessions:
        storage: cookie

The storage is always transparent to the final programmer. You'll always
able to use the session exactly like here, no changes are needed, also the
in operator works with each session backend.
"""

from spyro import *
from spyro.session import Session # first import the Session class

class Root(WebPage):
    """This example shows how to work with sessions.
    """
    
    def index(self):
        """Create the session and store a value.
        """
        
        # this will initialize or recovery the session
        sess = Session() # create the session object in the response method
        
        if self.request.method == 'POST':
            if self.request.form('name'):
                sess['name'] = self.request.form('name')
                self.response.redirect('/greet')
            else:
                self.response.redirect('/')
        else:
            self.response.write('''
<form method="POST" action="/">
    <label for="name">Your Name</label>
    <input type="text" name="name" />
    <input type="submit" />
</form>
''')
    
    def greet(self):
        """Use the 'in' operator to make sure the value exist, redirecting back
        otherwise.
        """
        
        sess = Session()
        if "name" in sess:
            self.response.write("Hello, %s" % sess["name"])
            self.response.write('<br><small><a href="/clear">Delete it</small>')
        else:
            self.response.redirect('/')
    
    def clear(self):
        """Destroy the session data.
        """
    
        sess = Session()
        sess.destroy()
        
        self.response.write("The session has been destroyed.")
        
        # try it redirecting on /greet
        self.response.redirect("/greet")
        
        
        
